package com.spring.redisson;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.redisson.api.RLock;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author liuzhiqiang
 */
public class Main {

    public static void main(String[] args) throws InterruptedException {
        RLock rLock = MyRedissonConfig.redisson().getLock("你好");
        if (rLock.isLocked() && rLock.isHeldByCurrentThread()) {
            rLock.unlock();
        }
        System.out.println("开始=======================================");
        new Thread(() -> {
            try {
//                rLock.lock(100,TimeUnit.SECONDS);
                // 看门狗失效
//                 if (rLock.tryLock(1000,2000, TimeUnit.MILLISECONDS)) {
                // 看门狗生效 等待 1秒, 锁30秒 2/3时间后 锁还存在则续约
                if (rLock.tryLock(1000, TimeUnit.MILLISECONDS)) {
                    try {
                        System.out.println("线程1获得所"+ DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                        Thread.sleep(60000);
                        System.out.println("线程1"+ DateFormatUtils.format(new Date(),"%yyyy-MM-dd HH:mm:ss"));
                    } finally {
                        if (rLock.isLocked() && rLock.isHeldByCurrentThread()) {
                            rLock.unlock();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        Thread.sleep(1000);
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                    if (rLock.tryLock(2000, TimeUnit.MILLISECONDS)) {
                        try {
                            System.out.println("线程2获得所"+ DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                            System.out.println("线程2"+ DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                        } finally {
                            if (rLock.isLocked() && rLock.isHeldByCurrentThread()) {
                                rLock.unlock();
                            }
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();


    }
}
